import DCYX_UNITS_API, {
  type UnitItem,
  type UserCurrentUnit,
  type UpdateUserCurrentUnitPayload,
  UnitQueryParams,
  UnitStudyStatsItem,
  type UpdateUnitStudyStatsPayload,
  UpdateStudyUnitStatusPayload,
  UnitStudyStatusItem,
} from '@/api/dcyx/units.api'
import {
  store,
  useDcyxProgramStoreHook,
  useDcyxSeriesStoreHook,
  useDcyxUserStoreHook,
} from '@/store'

export const useDcyxUnitStore = defineStore('dcyx_unit', () => {
  const currentUnit = ref<UserCurrentUnit>({} as UserCurrentUnit)
  const unitsList = ref<UnitItem[]>([])
  const loading = ref(false)
  const inited = ref(false)

  /**
   * 获取当前用户选择的单元
   * @returns {UserCurrentUnit | null}
   */
  function getCurrentUnit() {
    return new Promise<UserCurrentUnit | null>((resolve, reject) => {
      DCYX_UNITS_API.getCurrentUnit()
        .then((res) => {
          console.log('getCurrentUnit res', res)
          currentUnit.value = res
          resolve(res)
        })
        .catch((error) => {
          reject(error)
        })
        .finally(() => {})
    })
  }

  /**
   * 更新当前用户选择的单元
   * @param {UpdateUserCurrentUnitPayload} payload
   * @returns {Promise<void>}
   */
  function updateCurrentUnit(payload: UpdateUserCurrentUnitPayload) {
    loading.value = true
    return new Promise<void>((resolve, reject) => {
      DCYX_UNITS_API.updateCurrentUnit(payload)
        .then(() => {
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
        .finally(() => {
          loading.value = false
        })
    })
  }

  /**
   * 获取单元列表，通过 programId 获取
   * @param {UnitQueryParams} params
   * @returns {Promise<UnitItem[]>}
   */
  function getUnitsByProgramId(params: UnitQueryParams) {
    return new Promise<UnitItem[]>((resolve, reject) => {
      DCYX_UNITS_API.getUnitsByProgramId(params)
        .then((res) => {
          unitsList.value = res.list
          resolve(res.list)
        })
        .catch((error) => {
          reject(error)
        })
        .finally(() => {
          // loading.value = false
        })
    })
  }
  /**
   * 查询单元三模块的状态
   */
  async function getUnitStudyStatus(unitId: number) {
    return new Promise<UnitStudyStatusItem>((resolve, reject) => {
      const userId = useDcyxUserStoreHook().userInfo.id
      DCYX_UNITS_API.getUnitStudyStatus({
        unitId,
        userId,
      })
        .then((res) => resolve(res.list[0]))
        .catch((error) => reject(error))
    })
  }
  /**
   * 单元三学习模块统计信息
   */
  async function getUnitStudyStats(unitId: number) {
    return new Promise<UnitStudyStatsItem>((resolve, reject) => {
      const userId = useDcyxUserStoreHook().userInfo.id
      DCYX_UNITS_API.getUnitStudyStats({
        unitId,
        userId: userId,
      })
        .then((res) => resolve(res.list[0]))
        .catch((error) => reject(error))
    })
  }

  /**
   * 更新单元学习统计
   */
  function updateUnitStudyStats(payload: UpdateUnitStudyStatsPayload) {
    return DCYX_UNITS_API.updateUnitStudyStats(payload)
  }

  /**
   * 更新单元学习状态
   */
  function updateUnitStudyStatus(payload: UpdateStudyUnitStatusPayload) {
    return DCYX_UNITS_API.updateUnitStudyStatus(payload)
  }
  /**
   * 初始化单元 store
   *  1. 判断 loading 是否为 true，如果为 true 跳过；
   *  2. 查询用户是否选中 unit；
   *  3. 如果没有选中，则 currentUnit 为空；
   *  4. 如果存在选中的 unit，则 currentUnit 为选中单元；
   *  5. 并且根据 currentUnit 的 unitId 获取所有单元列表；
   *
   *  x. 最终 loading = true；
   */
  async function initUnitStore() {
    console.log('initUnitStore 开始初始化')
    console.log('initUnitStore inited', inited.value)
    if (inited.value) return

    console.log('initUnitStore 获取当前单元')
    const res = await getCurrentUnit()
    console.log('initUnitStore 获取当前单元 res', res)
    if (res) {
      currentUnit.value = res
      console.log('initUnitStore 获取当前单元 currentUnit', currentUnit.value)
      inited.value = true
    }
    // loading.value = false

    const res2 = await getUnitsByProgramId({
      programId: currentUnit.value.unitId,
      pageNum: 1,
      pageSize: 100,
    })
    unitsList.value = res2
    // loading.value = false

    // 设置 program 和 series 的 id
    useDcyxProgramStoreHook().setCurrentProgramId(currentUnit.value.programId)
    useDcyxProgramStoreHook().setCurrentSeriesId(currentUnit.value.seriesId)
    useDcyxSeriesStoreHook().setCurrentSeriesId(currentUnit.value.seriesId)
    useDcyxSeriesStoreHook().setCurrentSemesterId(currentUnit.value.semesterId)
  }

  /**
   * 清空 unit store
   */
  function resetUnitStore() {
    currentUnit.value = {} as UserCurrentUnit
    unitsList.value = []
    inited.value = false
    // 其他需要清空的状态可在此添加
  }

  return {
    currentUnit,
    unitsList,
    loading,
    inited,
    getCurrentUnit,
    updateCurrentUnit,
    getUnitsByProgramId,
    getUnitStudyStatus,
    getUnitStudyStats,
    initUnitStore,
    updateUnitStudyStats,
    updateUnitStudyStatus,
    resetUnitStore,
  }
})

export function useDcyxUnitStoreHook() {
  return useDcyxUnitStore(store)
}
